package com.samphanie.security.security.oauth.granter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.samphanie.common.enums.ResultCode;
import com.samphanie.common.execetion.ApiException;
import com.samphanie.common.service.IRedisService;
import com.samphanie.common.utils.RequestHolder;
import com.samphanie.security.domain.Captcha;
import com.samphanie.security.validation.properties.CodeConstant;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author ZSY
 * @email 1451691457@qq.com
 */
public class CaptchaTokenGranter extends AbstractTokenGranter {

    private static final String GRANT_TYPE = "captcha";
    private final AuthenticationManager authenticationManager;
    private IRedisService redisService;

    public CaptchaTokenGranter(AuthenticationManager authenticationManager,
                               AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService,
                               OAuth2RequestFactory requestFactory, IRedisService redisService) {
        this(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.redisService = redisService;
    }

    protected CaptchaTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices,
                                  ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {
        super(tokenServices, clientDetailsService, requestFactory, grantType);
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        HttpServletRequest request = RequestHolder.getHttpServletRequest();

        if (ObjectUtil.isNull(request)) {
            throw new ApiException(ResultCode.USER_ERROR_A0410);
        }

        Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
        // 增加验证码的判断
        String key = request.getHeader(CodeConstant.DEFAULT_PARAMETER_KEY);
        String code = parameters.get(CodeConstant.DEFAULT_PARAMETER_NAME_CODE);

        Captcha codeFromRedis = null;
        // 从Redis里读取存储的验证码信息
        try {
            Object obj = redisService.get(CodeConstant.CAPTCHA_KEY + key);
            codeFromRedis = (Captcha) redisService.get(CodeConstant.CAPTCHA_KEY + key);
        } catch (Exception e) {
            throw new ApiException("验证码不存在！");
        }

        if (StrUtil.isBlank(code)) {
            throw new ApiException("请输入验证码");
        }
        if (ObjectUtil.isNull(codeFromRedis) || codeFromRedis.isExpired()) {
            throw new ApiException("验证码不存在或已过期");
        }
        if (!StrUtil.equalsIgnoreCase(code, codeFromRedis.getCode())) {
            throw new ApiException("验证码不正确");
        }

        redisService.del(CodeConstant.CAPTCHA_KEY + key);
        String username = parameters.get("username");
        String password = parameters.get("password");
        // Protect from downstream leaks of password
        parameters.remove("password");

        Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password);
        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
        try {
            userAuth = authenticationManager.authenticate(userAuth);
        } catch (AccountStatusException | BadCredentialsException ase) {
            //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
            throw new InvalidGrantException(ase.getMessage());
        }

        // If the username/password are wrong the spec says we should send 400/invalid grant

        if (userAuth == null || !userAuth.isAuthenticated()) {
            throw new InvalidGrantException("Could not authenticate user: " + username);
        }

        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);

        return new OAuth2Authentication(storedOAuth2Request, userAuth);
    }
}
